use redis::{ Client, Connection };
use axum::Json;
use serde_json::Value;
use dotenv::dotenv;
use std::env;
use super::code;

pub fn connect(database:&str) -> Result<Connection, Json<Value>>{
    dotenv( ).ok( );
    let env_url = env::var("REDIS_URL").unwrap_or_default();
    let url = if env_url.is_empty() { config::REDIS_URL } else { &env_url };
    match Client::open(url.to_owned() + &database) {
        Ok(f) => {
            match f.get_connection() {
                Ok(conn) => Ok(conn),
                Err(e) => Err(code::sys_("Redis 数据库连接错误：".to_string() + &e.to_string()))
            }
        },
        Err(e) => Err(code::sys_("Redis 数据库连接错误：".to_string() + &e.to_string()))
    }
}